package cn.edu.ctbu.dp01.service;

import cn.edu.ctbu.dp01.dao.StudentRepository;
import cn.edu.ctbu.dp01.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;

    public List<Student> getAll() {
        return studentRepository.findAll();
    }

    public List<Student> findByConditions(String name, String tno, String sex) {
        if (name != null && !name.isEmpty()) {
            return studentRepository.findByNameContaining(name);
        }
        if (tno != null && !tno.isEmpty()) {
            return studentRepository.findByTno(tno);
        }
        return studentRepository.findAll();
    }

    public Student findById(int id) {
        return studentRepository.findById(id).orElse(null);
    }

    public Student add(Student student) {
        return studentRepository.save(student);
    }

    public Student update(Student student) {
        return studentRepository.save(student);
    }

    public void delete(Integer id) {
        studentRepository.deleteById(id);
    }

    public List<Student> findByName(String s) {
        return studentRepository.findByNameContaining(s);
    }
}